package com.gmrz.uap.job;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.datastatistics.DataStatisticsService;
import com.gmrz.uap.model.Authenticators;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 每天更新用户状态
 */
public class UpdateUserStatusDayJob implements Job {
    private static final Logger LOG = LoggerFactory.getLogger(UpdateUserStatusDayJob.class);
    private static boolean lock = false;
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {//根据随机生成的随机毫秒数来进行休眠
            Thread.sleep(DataStatisticsService.me.getRandomSleepMinutes());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!lock) {
            String key = TaskConst.UPDATEUSERSTATUSDAYJOB_CACHE_KEY;
            key = key + DateUtil.getToday();
            boolean flag = false;
            try {
                lock = true;
                flag = AmmsCacheUtil.getCacheStoreService().tryGetDistributedLock(key,TaskConst.JOB_CACHE_VALUE,TaskConst.AAIDSTATISTICSDAYJOB_CACHE_TiME);
                if(flag) {
                    String daysString = UasConfig.dao.getValueByKey("uaf.authenticator.overdue.days");
                    int days = 0;
                    if (null != daysString && !"".equals(daysString.trim())) {
                        days = Integer.parseInt(daysString);
                    }
                    if (days > 0) {
                        Calendar cal = Calendar.getInstance();
                        cal.add(Calendar.DAY_OF_YEAR, 0 - days);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String dateStr = simpleDateFormat.format(cal.getTime());
                        LOG.info("UpdateUserStatusDayJob execute update authenticator status start date=" + dateStr);
                        Date date = simpleDateFormat.parse(dateStr);
                        int count = Authenticators.dao.updateAuthenticatorStatus(date);
                        LOG.info("UpdateUserStatusDayJob execute update authenticator status end count=" + count);
                    }
                }
            }catch(Exception e){
                LOG.error("UpdateUserStatusDayJob execute error",e);
            }finally {
                lock = false;
                if(flag){
                    AmmsCacheUtil.getCacheStoreService().releaseDistributedLock(key,TaskConst.JOB_CACHE_VALUE);
                }
            }
        }
    }
}
